<template>
  <div class="login-page">
    <van-nav-bar
      right-text="注册"
      title="登录"
      :left-arrow="history.length > 2"
      :left-text="history.length > 2 ? '返回' : ''"
      fixed
      @click-left="$router.back()"
      @click-right="$router.push('/register')"
    />
    <!-- 头部 -->
    <div class="login-head">
      <h3>{{ isSwitchover ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isSwitchover = !isSwitchover">
        <span>{{ isSwitchover ? '短信验证码登录' : '密码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <van-form autocomplete="off" @submit="submit" ref="formRef">
      <van-field
        name="mobile"
        placeholder="请输入手机号"
        type="tel"
        maxlength="11"
        v-model="form.mobile"
        :rules="mobileRules"
      ></van-field>
      <van-field
        v-if="isSwitchover"
        placeholder="请输入密码"
        :type="isShowPassword ? 'text' : 'password'"
        :right-icon="isShowPassword ? 'eye-o' : 'closed-eye'"
        maxlength="24"
        v-model="form.password"
        :rules="passwordRules"
        @click-right-icon="isShowPassword = !isShowPassword"
      ></van-field>
      <van-field
        v-else
        v-model="form.code"
        placeholder="请输入验证码"
        maxlength="6"
        type="tel"
      >
        <template #button
          ><span class="btn-send" @click="send" v-if="!isCountDown"
            >发送验证码</span
          >
          <van-count-down
            v-else
            :time="10 * 1000"
            format="ss秒后再次发送"
            @finish="isCountDown = false"
        /></template>
      </van-field>
      <div class="cp-cell">
        <van-checkbox v-model="isAgree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit"
          >登 录</van-button
        >
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <div class="icon">
        <img src="@/assets/qq.svg" alt="" />
      </div>
    </div>
  </div>

  <svg aria-hidden="true">
    <!-- #icon-文件夹名称-图片名称 -->
    <use href="#icon-login-eye-off" />
    <use href="#icon-login-eye-on" />
  </svg>
</template>

<script setup lang="ts">
import { getMobileCode, loginByCode, loginByPassword } from '@/api/user'
import { useUserStore } from '@/stores'
import { mobileRules, passwordRules } from '@/utils/rules'
import { showFailToast, showSuccessToast, type FormInstance } from 'vant'
import { ref } from 'vue'
import { reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
defineOptions({
  name: 'LoginIndex'
})

const form = reactive({
  mobile: '',
  password: '',
  code: ''
})

const history = window.history
const router = useRouter()
const route = useRoute()
const isAgree = ref(true) // 是否同意勾选
const isShowPassword = ref(false) // 切换密码登录与验证码登录
const isCountDown = ref(false) // 是否开启验证码倒计时
// 切换密码登录与验证码登录
const formRef = ref<FormInstance>()
const isSwitchover = ref(true)

const submit = async () => {
  // 1. 协议校验
  if (!isAgree.value) return showFailToast('请勾选协议')
  // 2. 调接口提交数据
  // 把用户填写的数据传给后台，获取这个用户的token
  const { mobile, code, password } = form
  const res = isSwitchover.value
    ? await loginByPassword({ mobile, password })
    : await loginByCode({ mobile, code })
  // 3. 成功提示
  showSuccessToast('登陆成功')
  // 4. 存储token
  const store = useUserStore()
  store.setUser(res.data)
  // 5. 跳转user页
  if (route.query.returnUrl) {
    router.replace({ path: route.query.returnUrl as string })
  } else {
    router.push('/user')
  }
}

// 验证码
const send = async () => {
  // 1. 校验手机号是否合法，不合法阻止并提示
  const mobileRule = await formRef.value?.validate('mobile').catch((err) => err)
  if (mobileRule) return showFailToast(mobileRule.message)

  // 4. 即将调接口发送验证码，开启倒计时读秒
  isCountDown.value = true
  // 2. 合法调接口
  const sendMobileCode = await getMobileCode({
    mobile: form.mobile,
    type: 'login'
  })
  console.log(sendMobileCode)

  showSuccessToast(sendMobileCode.message)
  // 3. 成功提示
}
</script>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    display: flex;
    padding: 30px 30px 50px;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
.van-count-down {
  color: var(--cp-primary);
}
</style>
